Dreamweaver Article

How to Develop an Online Shopping Cart (Part Three)

Lawrence Cramer
www.cartweaver.com

This is part three of a three-part series on shopping carts. In my previous two articles, I discussed the theory and principles behind developing an e-commerce application. In this article, I will deconstruct the example application that I referred to in the previous two articles to show how I put some of the principles into practice. If you haven't already been through part one and part two of this article series, do so before completing part three. You can see a hosted version of the shopping cart covered in this part of the article series.

I built the example application in Macromedia ColdFusion using Macromedia Dreamweaver MX 2004, but the principles I cover apply to virtually all server platforms. I'm not going to spend a great deal of time on the specifics of every line of code in the shopping cart application, but I will review the major code blocks on each of the application pages. If you are new to ColdFusion and you don't understand parts of the code in the sample files, a good place to go for help is the built-in ColdFusion reference in Dreamweaver (Window > Reference). Some good places to start learning ColdFusion are the ColdFusion Developer Center, or one of the many ColdFusion books on the market. Again, this article isn't meant to be a ColdFusion how-to article as much as it is meant to show you the process of developing an e-commerce application.

Note: The example application in the download files is not meant to be a production-ready shopping cart and does not include the SSL security described in parts one and two of this article series.

Requirements

Dreamweaver MX 2004


ColdFusion MX (Optional for running the example application)


Tutorials and sample files:


Microsoft Access (Optional for viewing example application database)

 

Setting Up the Sample Files

Installing ColdFusion MX is optional and unnecessary for deconstructing the shopping cart in this article. However, you will need it if you want to run the example application. If you do not plan to install ColdFusion and run the example application, you can still see a hosted version of the application running here. If you do not plan to run the shopping cart application locally, you will still need to download and unzip the sample files linked from the beginning of this article to be able to follow along. If you do not plan to run the shopping cart application locally, you can skip to the next page of the article.

Note: Again, the example application in the download files is not meant to be a production-ready shopping cart and does not include the SSL security described in parts one and two of this article series.

If you plan to run the example application locally and have not already done so, download the example application in the sample files linked from the beginning of this article. Keep in mind that you need to have ColdFusion MX installed to run this example application. You can get a trial version of ColdFusion MX from using the link at the beginning of this article. Installing ColdFusion is beyond the scope of this article. Consult the ColdFusion Support Center for troubleshooting the installation of ColdFusion MX. Use the following steps to install the example application.

  1. If you plan to run the example application and have installed ColdFusion MX, create a folder called cart in the wwwroot directory under the CfusionMX directory (C:\CFusionMX\wwwroot\cart). This assumes you are using the default JWS web server installation and not the installation for a third-party web server such as IIS or Apache.
  2. Next, unzip the example files into your new cart folder.
  3. Open Dreamweaver MX and create a new site and map the new site to the Example files folder.
  4. Finally, if you are running CFMX, create a Data Source Name called "DevNetExample" in ColdFusion Administrator and browse to the Access database file in you site (See ColdFusion MX documentation if you are not familiar with how to do this.).

The Database

As I mentioned in parts one and two of this article series, the database is the most critical component of an e-commerce application. Once you have designed and populated database, you will have customer and order records—possibly thousands of them. Changing the database structure is extremely difficult once the database has data in it. Even though the sample database is quite simple, you still need to ensure that you keep data and referential integrity in mind and build a database that can be scaled so that it will stand the test of time.

The example application uses a Microsoft Access database. Even if you are going to deploy to a more robust database such as SQL Server, Access is a great tool for mocking up and testing a database.

Note: I'm going to assume you are somewhat familiar with Microsoft Access. If you aren't, you may want to read some more and get acquainted with it. If you are planning on developing dynamic web applications on the Microsoft Windows platform, doing so will be well worth your effort. If you plan to develop applications using databases (such as MySQL) on non-windows platforms, you will still be able to learn from the below database description. However, some things such as datatype names of the database table fields may differ. Also, the screenshots below only apply to Access. Even if you are primarily a web designer, possessing a basic knowledge of how databases function will go a long way in improving your ability to deliver quality dynamic applications.

Here is a general overview of the tables and fields in the database and the relationships between them.

The database

Figure 1. The database

(+) View larger

I will guide you through each of the database tables, review the fields and data types, and explain how they work in the application.

Administration Users Table:

The Administration Users table stores the usernames and passwords that your app will use to gain access to the application's administrative back end. Here is what it contains.

Admin Table:

Field Name

Data Type

Field Size

Other Parameters

AdminID

AutoNumber

Long Integer

Key Field

uName

Text

100

Leave Default

uPassword

Text

50

Indexed: Yes (No Duplicates)

In the Access Design View the table looks like the following:

The AdminUsers table in Access Design View

Figure 2. The AdminUsers table in Access Design View

Notice the key icon next to the AdminID. This shows that this field is the unique index for this table. Each table must have a unique primary key field to identify records. To set the primary key field in Access, click the name of the field (in this case AdminID). Next, right click Select Primary Key from the pop-up menu. To set the data type parameters, click the Field Name you wish to edit. Choose the Name field this time. As shown in Figure 3 below, you'll notice that the bottom of the Design view window has a window tab named General.

The Name field parameters

Figure 3. The Name field parameters

This is where you set the data type parameters. For the Name field, leave all the options in the default setting except for the Field Size. Set the Field Size parameter to 100. This means the Name field will hold up to 100 characters.

Items Table

The Items table stores the items that are for sale. The Items table holds the following data: the name of the item, a memo field to store the description, the price, and the name of the image file. You'll notice that the example database only stores the name of the image. It's never a good idea to store the directory path to the images in the database ( …/images/imagename.gif). If you need to move the image files later, all of the data in your image fields becomes invalid and you'll have to update all your records. To avoid this, always have the directory path to the images in your application code where you can more easily update it.

Items Table:

Field Name

Data Type

Field Size

Other Parameters

ItemID

AutoNumber

Long Integer

Key Field

ItemName

Text

100

Leave Default

ItemDiscrip

Memo

 

Leave Default

ItemPrice

Currency

 

Leave Default

ItemImage

Text

50

Leave Default

Customer Table

The customer information is stored in the Customer table. You'll notice that I'm not storing the customer data and the order data together in the same table. The first rule of good database design is to eliminate duplicate data. Storing the customer information with the order information would result in a lot of duplicate data if the same customer had several orders.

Customer Table:

Field Name

Data Type

Field Size

Other Parameters

custID

AutoNumber

Long Integer

Key Field

custName

Text

150

Leave Default

custAddress

Text

150

Leave Default

custCity

Text

50

Leave Default

custState

Text

50

Leave Default

custZip

Text

25

Leave Default

Storing Orders

Next, you need a place to store the orders. This presents a challenge. If the customer orders more than one product, you could create a line for each item, but this would result in a lot of duplicate data if you repeated the order ID, date, and total on each line. To avoid this situation, write the order data to two related tables. One table will store data that is unique to each order: order ID, the customer ID, the amount of the order, and the order date. The second table will store the items ordered.

Orders Table:

Field Name

Data Type

Field Size

Other Parameters

orderID

AutoNumber

Long Integer

Key Field

orderCustID

Number

Long Integer

Leave Default

orderTotal

Currency

 

Leave Default

orderDate

Date/Time

ShortDate

Now()

Next, create the Order Items table to store the items ordered.

OrdersItems Table:

Field Name

Data Type

Field Size

Other Parameters

orditmID

AutoNumber

Long Integer

Key Field

orditmOrderID

Number

Long Integer

Leave Default

orditmItemID

Number

Long Integer

Leave Default

orditmQty

Number

Long Integer

Leave Default

Data Relationships

Look at Figure 1 above and notice the relationships between the tables. These are depicted by the lines between the tables. The Customer ID relates the Customer table to the Orders table. This allows your shopping cart application to know what orders belong to a given customer. The OrderID relates the OrderItems Table to the Orders table. Finally, the ItemsID relates the OrderItems table to the Items table.

These relationships allow your shopping cart application to keep track of what customers have ordered and what items were in each order. You can even enforce referential integrity so a customer record cannot be deleted if there is an order record associated with it. This will keep the application from creating orphan records, which are orders that have no Customer related to them.

Next, we'll take a look at the application files. I'll highlight the main points in the code to show what is going on, but I recommend that you take some time to look over the files carefully in the Dreamweaver Code view. I've commented the code quite extensively to document what it is going on.

Application.cfm

As you will recall from part one of this article series, the web is stateless. In other words, web servers don't remember anything. So, the first thing you need to do is set up a way for the shopping cart application to remember what a customer selects—a virtual shopping cart. There are several ways to do this depending on the server model you are using. For this example, you will be using session variables to maintain state in the shopping cart application or remember/persist information about a visitor and their shopping cart session.

In ColdFusion, the Application.cfm file is a file that executes at the beginning of every file requested by the browser. This makes it the ideal place to store Global parameters, or information that is needed on every page in the shopping cart application. The code we're most interested with in the Application.cfm file is the cfapplication tag.

<cfapplication
name="DevNetECart" 
sessionmanagement="yes">	

Notice the sessionmanagement attribute in the cfapplication tag. This is used to turn session management on for your application and will allow you to use session variables for the cart, which brings you to the next file.

inc_DevNetCart.cfm

Here is the brain of the cart application. This file creates the cart session if it doesn't yet exist, adds items to it, and if an item is already in the cart session, it will update quantities if needed.

First, you wrap everything in an IF statement with a cfif tag.

<cfif IsDefined('FORM.Submit')>
<!---code to be executed if the form has been submitted --->
<cfif>

Doing this will keep the code it wraps from being executed unless the add-to-cart form is submitted. If the add-to-cart form is submitted, the code which it wraps will be used to take the appropriate action. The next code of interest starts on line 22 of the inc_DevNetCart.cfm file.

<cfif IsDefined('Session.Cart') is "NO"> 
<cfscript> 
Session.Cart=StructNew();
Session.Cart.ItemID=ArrayNew(1); 
Session.Cart.Qty=ArrayNew(1); 
</cfscript> 
</cfif>

If this is the first item a user is adding to their cart, this code will create a new cart session for the user. In ColdFusion, sessions can contain complex data. This allows you to use a structure containing arrays, and makes it easy to keep all of the cart data for any given user in one place. Although session variables have a few drawbacks, such as they do not persist from user visit to visit, or across servers such as in a clustered environment, or with shared SSLs, they are fast and convenient. This makes session variables a good choice for this simple shopping cart application.

The next block of code performs two important functions. First, it checks to see if the item being added is already in the cart. Second, if the item being added isn't already in the cart, it adds it. If the item being added to the cart is already in the cart, it updates the quantity of that item in the cart.

<!--- //If Item exists, Update Quantity // ---> 
<cfif ListFind(ArrayToList(Session.Cart.ItemID),FORM.ItemID) NEQ 0> 
<cfset ThisItem=ListFind(ArrayToList(Session.Cart.ItemID),FORM.ItemID)> 
<!--- //Set Quantity // ---> 
<cflock timeout="2" throwontimeout="No" type="EXCLUSIVE" scope="SESSION"> 
<cfset Session.Cart.Qty[ThisItem]=Session.Cart.Qty[ThisItem] + FORM.Qty> 
</cflock> 
<cfelse> 
<!--- If the Item doesn't exist in the Cart Session, add it. ---> 
<cfset ThisItem=ArrayLen(Session.Cart.ItemID) +1 > 
<!--- === [ Add to cart ] === // ---> 
<cflock timeout="5" throwontimeout="No" type="EXCLUSIVE" scope="SESSION"> 
<cfset Session.Cart.ItemID[ThisItem]=FORM.ItemID> 
<cfset Session.Cart.Qty[ThisItem]=FORM.Qty> 
</cflock> 
</cfif> 

That's all there is to the Application.cfm and inc_DevNetCart.cfm files. As mentioned above, the Application.cfm file is a file that executes at the beginning of every file requested by the browser. If you view the HTML source code for any of the cart pages in your browser (View > Source), you'll notice that none of this code is visible to the user. This code is also separate from the ColdFusion code in the other pages in the shopping cart. It is a good practice to separate your function code from your presentation code as much as possible. Doing so will allow you to change and modify the design of your site with out impacting the functionality of the application. This will save you many hours of work and headaches later.

Index.cfm—The Shopping Cart Home Page

Index.cfm is the home page and where you display what you have to sell and allow users to add items to their cart. Open index.cfm in the Code view, and look at line 18.

<cfinclude template="inc_DevNetCart.cfm">

Here, include the inc_DevNetCart.cfm file I just discussed. Using SSIs (server-side includes) is a great way to separate functionality from presentation code. You can add this cart function to many pages across the application, and if you need to change something in the cart code, you only need to do it once on the included page. As a result, every page in the application that uses the included page will be automatically updated.

Next on the index.cfm page, I have a standard query that retrieves the cart items from the database and displays the products in a standard HTML table. There are a couple of things to point out here On line 43 of index.cfm, notice another server-side include. This calls a file that will show the user what is in their cart if a cart session exists. We will look at that file in a minute. Next, from lines 48 to 84 see that the cfoutput tag wraps a table row as shown in the code snippet below.

<cfoutput query="getItems">
<tr> 
<td width="36%"> 
<!--- The image file name is dynamically populated from the Items table in the database. ---> 
<img src="images/#getItems.itemImage#">
</td> 
<td width="64%"><table width="90%" border="0" align="center" cellpadding="2" cellspacing="2"> 
<tr> 
<td class="subhead">#getItems.itemName#</td> 
</tr> 
<tr> 
<td>#getItems.itemDiscrip# </td>
</tr> 
<tr> 
<td> 
<form name="form" method="post" action="#variables.ThisPage#"> 
<table width="100%" border="0" cellspacing="0" cellpadding="0"> 
<tr> 
<td width="25%">Price: #LSCurrencyFormat(getItems.itemPrice,'local')#</td> 
<td width="25%" align="center"><input name="Qty" type="text" id="Qty" value="1" size="4"></td> 
<td width="50%" align="center"><input name="ItemID" type="hidden" id="ItemID" value="#getItems.itemID#"> 
<input name="Submit" type="submit" class="buttons" value="add to cart">
</td> 
</tr> 
</table> 
</form> 
</td> 
</tr> 
</table> 
</td> 
</tr> 
<tr> 
<td colspan="2"> 
<hr> 
</td> 
</tr> 
</cfoutput>

Doing this creates a loop that will generate one table row for each record found in the Items table in the database. This is known as a Repeat Region server behavior in Dreamweaver MX and you can find it in the Server Behavior tab of the Application panel group.

In this table row, I display the item data, and the image. Notice that the image name is generated dynamically by using the file name stored in the database. I also have a form that allows the user to enter a quantity and add an item to his cart.

inc_DisplayDevNetCart.cfm

Now, open the inc_DisplayDevNetCart.cfm file in the Code view. This file contains the code you use to show what a user has in his cart. This code is contained in a cfif tag that keeps the code from executing if no cart session exists. The cfif tag causes the code to execute if a cart session exists. Again, notice that I use an server-side include to reuse this code throughout the site. Includes are a great tool for reusing code and simplifying your site maintenance duties.

Next, I'll take you through the shopping cart's checkout page.

Checkout.cfm

In the checkout page, I provide the user with details of what she has in her cart, what the order total is, and I present her with an order form. Open checkout.cfm in the Code view. The code between lines 52 and 71 of the checkout.cfm page shows what's in the cart.

<cfset ordertotal = 0> 
<cfloop from="1" to="#ArrayLen(Session.Cart.ItemID)#" index="ThisItem"> 
<cfquery name="geItem" datasource="DevNetExample"> 
SELECT itemPrice,itemID,itemName 
FROM Items 
WHERE itemID = #Session.Cart.ItemID[ThisItem]# 
</cfquery> 
<cfset total = 0> 
<cfset total = total + (geItem.itemPrice * Session.Cart.Qty[ThisItem]) > 
<cfoutput> 
<span class="txt-bold">ItemID: #Session.Cart.ItemID[ThisItem]#| Quantity: #Session.Cart.Qty[ThisItem]# | Total: #LSCurrencyFormat(total,'local')#<BR> 
</span></cfoutput><span class="txt-bold"> 
</span> 
<cfset ordertotal = ordertotal + total> 
</cfloop></td>
<td valign="top"> 
<span class="txt-bold"><cfoutput>#ordertotal#</cfoutput></span><br>

Here I also create the final cart total that the app will be pass to the orders table in the database. In the form that follows this code on line154, you'll find a hidden form field I use to pass the order total to the Process Order/Confirmation page.

ProcessOrder.cfm

On the ProcessOrder.cfm page, the shopping cart processes the order and gives the user a confirmation message. Open ProcessOrder.cfm in the Code view. Notice a comment on lines 29 through 37 that says this is where you would put the code to authorize the shopper's credit card data. There are a couple of good real-time gateway custom tags for Authorize Net and Verisign PayFlo Pro on the Macromedia ColdFusion Exchange that would work nicely here. You could look at using PayPal as well, although since PayPal is not a real-time processor and requires a jump to their servers to complete the transaction, you would need to modify your app.

Writing Data to the Database

Next, assuming the payment verified, the application writes the order to the database. First, the application adds the customer using the following cfquery database insert code.

<cfquery datasource="DevNetExample"> 
INSERT INTO customers (custName, custAddress, custCity, custState, custZip) 
VALUES ('#FORM.custName#', '#FORM.custAddress#', '#FORM.custCity#', '#FORM.custState#', '#FORM.custZip#') 
</cfquery>

Then, the application retrieves the customer ID it just created in the above cfquery insert and uses the customer ID when it adds the data to the orders table.

<!--- Insert the Order Total and crate an Order record --->
<cfquery datasource="DevNetExample">
INSERT INTO Orders (orderCustID,orderTotal) 
VALUES (#getNewCutID.NewCustomerID#, #form.orderTotal#) 
</cfquery>

Again, the application retrieves the order number it just created and uses the order number when it loops through the cart and adds the order items to the OrfderItems table.

<!--- Get the ID of the Order Record we just created --->
<cfquery name="getNewOrderID" datasource="DevNetExample">
SELECT MAX (orderID) AS NewOrderID 
FROM Orders 
</cfquery>

And finally, the application loops through the cart session array and adds the items for this order to the database.

<!--- Now loop through the Cart Array and create a record in the Order Items table relate the foreign Key field to the Orders table. ---> 
<cfloop from="1" to="#ArrayLen(Session.Cart.ItemID)#" index="ThisItem">
<cfquery datasource="DevNetExample"> 
INSERT INTO OrderItems (orditmOrderID,orditmItemID,orditmQty) 
VALUES (#getNewOrderID.NewOrderID#, #Session.Cart.ItemID[ThisItem]#, #Session.Cart.Qty[ThisItem]#) 
</cfquery> 
</cfloop>

And that's it! A thank you message displays to the customer.

One last thing to notice on the ProcessOrder.cfm page is the code found on lines 115 through 118.

<!--- //All Done Now ... Need to Kill Session // ---> 
<cflock timeout="10" throwontimeout="NO" type="EXCLUSIVE" scope="SESSION"> 
<cfset StructDelete(session, "cart") > 
</cflock>

This code clears the cart session. Since the customer is finished, you want to delete the cart session just in case the customer hits the back button or goes back into the site to look around some more. We don't want the cart session hanging around and causing possible confusion.

Administration

Finally, let's take a quick look at the administration section of the shopping cart application. I won't go into much detail here. In it's current state, the application just shows the orders and the customers using standard Dreamweaver Dynamic Table Server behaviors. Something I will guide you though is the how to secure the admin section of the application from unauthorized users. Obviously, you don't want just anyone looking at the sales and customer information, so I set up a simple but very effective user authorization system.

admin/Application.cfm

Since the administration section of the application has its own global parameters, I use another Application.cfm file to set these. Using multiple Application.cfm files in a single application works fine for ColdFusion due to the fact that the ColdFusion server will look up the directory tree from the current open file to find the first Application.cfm file it comes to and then uses that Application.cfm file. Since this file is in the admin section's root, this is the Application.cfm file that the ColdFusion server will use for pages in the admin directory of the application.

Open the Application.cfm file in the admin directory in Code view. Notice once again that sessions are enabled, and you'll see a section of code where the user is logged out. See below.

<!--- If the admin user clicks "Log Out" kill "Logged In" session. --->
<cfif IsDefined ('URL.logout')> 
<cflock timeout="10" throwontimeout="NO" type="EXCLUSIVE" scope="SESSION">
<cfset StructDelete(session, "LoggedIn") >
</cflock>
</cfif>
If a user clicks the Log Out link anywhere in the admin section,, their authorization session will be deleted and they will be returned to the log on page.

admin/index.cfm

Open the index.cfm page in the admin directory. Here the user is presented with a log on form. When a user enters a username and password and submits the form, the form action submits back to this same page and invokes the authorization code found on lines 18 through 34 as shown below.

<!--- If Form was submitted Log in user ---> 
<cfif IsDefined ('FORM.Name')> 
<!--- Run query to check username and password ---> 
<CFQUERY NAME="getAuth" DATASOURCE="DevNetExample"> 
SELECT adminID 
FROM adminUsers 
WHERE uName = '#FORM.Name#' 
AND uPassword = '#FORM.Password#' 
</CFQUERY> 
<!--- If Log on was good, set as authorized ---> 
<cfif getAuth.RecordCount EQ 1 > 
<cflock timeout="9" throwontimeout="no" type="exclusive" scope="session"> 
<cfset Session.LoggedIn = getAuth.adminID> 
</cflock> 
<!--- Go To Admin Home ---> 
<cflocation url="adminHome.cfm" addtoken="no"> 
</cfif> 
</cfif>

If the username and password used is found in the AdminUsers table, a logged in session is set and the user is taken to the administration home page (adminHome.cfm). If no match is found, nothing happens and the user is left on this page.

inc_AuthAdmin.cfm

One other file I will take a moment to discuss is the AuthAdmin server-side include file. This simple include file is placed at the very top of every page in the Admin directory of the application.

<cflock timeout="9" throwontimeout="no" type="readonly" scope="session"> 
<cfif NOT IsDefined ('Session.LoggedIn')> 
<cflocation url="AdminHome.cfm" addtoken="no"> 
</cfif> 
</cflock>

The code shown here checks to see it the user requesting the page is logged in and authorized to see the page. If not, the user is redirected to the log on page (admin/index.cfm) and none of that page is shown or executed. As long as this include is at the top of every page in the admin directory of the application, no one will be able to see any of the Admin data without first logging in.

This brings us to the end of our three-part series. I hope you've enjoyed it. Be sure to take the time to peruse through the code of the example application and look at the code comments. Although this is a very simple application, all the basic elements of an e-commerce application are there with the exception of the secure socket layer (SSL) features mentioned in parts one and two. Combined with the principles covered in the first two articles, you'll be well on your way to being able to develop solid, functional e-commerce applications.

If you have any comments or questions, please feel free to drop me a line!


About the author

Lawrence's day job is web application development. He also develops Dreamweaver Extensions, helps out on the Macromedia forums, teaches at the local Community College, speaks at web development conferences around the country, and writes articles on web development and e-commerce. For fun, he takes motorcycle road trips and occasionally catches a fish or two with his wife of 25+ years. Lawrence has three children—two daughters and one son. Two are grown and one is still in school. You can find him at lawrence@cartweaver.com.